<?php
require_once('includes/appInit.php');
include('includes/ajax/sysData.php');
include('includes/ajax/ajaxResources.php');

if ($_POST['upload'] == 1) {
	//echo 'Uploading';
	/*
	 * Step 1: Just upload the file as-is to public_files/temp
	 */
	$someFile     = $_FILES['fileUpload']['tmp_name'];
	$someFileName = $_FILES['fileUpload']['name'];
	$someFileType = $_FILES['fileUpload']['type'];
	$someFileSize = $_FILES['fileUpload']['size'];
	$filePath = PUBLIC_FILES_PATH.'temp/'.$someFileName;
	if (move_uploaded_file($someFile, $filePath)) {
		$return['status'] = 'SUCCESS';
        $return['msg']    = 'File uploaded.';
        $return['location'] = '';
        $return['filename'] = $someFileName;
	}
}
if ($_POST['fileDetails'] == 1) {
	$error = 0;
	
	if ($error != 1) {
		/*
		 * Step 2: Dump file details to database and move file into 
		 * appropriate directory.
		 */
		$phpJSON  = $_POST['jsonString'];
		$phpJSON  = urldecode(stripslashes($phpJSON));
		$phpArray = Zend_Json::decode($phpJSON);
		
		$someFileName = $phpArray['fileName'];
		$fileCat      = $phpArray['catID'];
		$fileSubCat   = $phpArray['subCatID'];
		$fileTitle    = fieldToDB($phpArray['fileTitle']);
		$fileDesc     = fieldToDB($phpArray['fileDesc']);		
			
		// Clean Filename
		$filename = cleanString($someFileName);		
		$fileDir  = PUBLIC_FILES_PATH.'resource_files/';			
			
		/*
		 * Get directory name from category table
		 */
		if ($fileCat>0) {
			$sql = "SELECT DirectoryName 
					FROM cdc_sysCategory 
					WHERE CatID = '$fileCat'";
			$result = mysql_db_query($dbname,$sql);
			$row = mysql_fetch_assoc($result);
			$dirName = $row['DirectoryName'];
		
			if (!empty($fileSubCat) && ($fileSubCat != 'Select...') ) {
				$sql = "SELECT DirectoryName 
					FROM cdc_sysCategory 
					WHERE CatID = '$fileSubCat'";
				$result = mysql_db_query($dbname,$sql);
				$row = mysql_fetch_assoc($result);
				$fileCat = $fileSubCat;
				$dirName .= '/'.$row['DirectoryName'];
			}			
			
			$destFilePath = $fileDir.$dirName.'/'.$filename;		
			$oldFilePath  = PUBLIC_FILES_PATH.'temp/'.$someFileName;			
			rename($oldFilePath,$destFilePath);
		}	
		
		// Add file to database
		if ($_SESSION['userLevel'] == 1) {
			$approved = 1;
		} else {
			$approved = 0;
		}
		$approved = 1;		
		
		$sql = "INSERT into cdc_Files (
				CatID,
				FileTitle,
				FileDesc,
				FileName,
				FileSize,
				FileType,
				Approved,
				DateUpdate,
				Userid
				) values (
				'$fileCat',
				'$fileTitle',
				'$fileDesc',
				'$filename',
				'$someFileSize',
				'$someFileType',					
				'$approved',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'					
			)";
		
		$result = mysql_db_query($dbname,$sql);	
	}
	$return['status'] = 'SUCCESS';
    $return['msg']    = $msg;
    $return['location'] = '';
    $return['filename'] = $someFileName;
}	

echo json_encode($return);
exit;
?>